using AutoMapper;
using KayakMes.Common;
using KayakMes.Common.Dtos.TeamDTO.Input;
using KayakMes.Common.Dtos.TeamDTO.Output;
using KayakMes.Common.Result;
using KayakMes.ProcessManagement.Domain.SchedulingModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace KayakMes.ProcessManagement.Application.Scheduling
{
    public class EmployeeService : IEmployeeService
    {
        private readonly BaseReposiotry<EmployeeModel> _employeeRepository;
        private readonly BaseReposiotry<TeamSetModel> _teamSetRepository;
        private readonly IMapper _mapper;

        public EmployeeService(BaseReposiotry<EmployeeModel> employeeRepository, 
                             BaseReposiotry<TeamSetModel> teamSetRepository, 
                             IMapper mapper)
        {
            _employeeRepository = employeeRepository;
            _teamSetRepository = teamSetRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加员工信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> Add(EmployeeInput input)
        {
            var entity = _mapper.Map<EmployeeModel>(input);
            entity.Id = YitIdHelper.NextId();
            var res = _employeeRepository.Add(entity);
            if (res > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "添加员工信息成功",
                    Data = res
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "添加员工信息失败",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 删除员工信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<int> DeleteEmployee(long id)
        {
            var query = _employeeRepository.GetModel(id);
            if (query != null)
            {
                var res = _employeeRepository.Delete(query);
                if (res > 0)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Success,
                        Message = "删除员工信息成功",
                        Data = res
                    };
                }
                else
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "删除员工信息失败",
                        Data = 0
                    };
                }
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "找不到要删除的员工信息！",
                    Data = -1
                };
            }
        }

        /// <summary>
        /// 根据ID查询员工信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<EmployeeOutput> FindEmployee(long id)
        {
            var query = _employeeRepository.GetModel(id);
            if (query != null && id > 0)
            {
                var entity = _mapper.Map<EmployeeOutput>(query);
                return new ApiResult<EmployeeOutput>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询员工信息成功",
                    Data = entity
                };
            }
            else
            {
                return new ApiResult<EmployeeOutput>()
                {
                    Code = ApiEnums.Fail,
                    Message = "找不到要查询的员工信息！",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 查询员工列表（无条件查询）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiPaging<EmployeeOutput> GetEmployeeList(GetEmployeeInput input)
        {
            var employees = _employeeRepository.GetAll().Where(x =>x.TeamSetId == 0).ToList();

            

            int total = employees.Count();
            var entity = _mapper.Map<List<EmployeeOutput>>(employees);
            

            return new ApiPaging<EmployeeOutput>()
            {
                Items = entity,
                Total = total,
                Code = ApiEnums.Success,
                Message = "获取员工列表成功",
                PageIndex = input.PageIndex,
                PageSize = input.PageSize,
            };
        }

        /// <summary>
        /// 根据班组ID查询员工列表
        /// </summary>
        /// <param name="teamSetId"></param>
        /// <returns></returns>
        public ApiPaging<EmployeeOutput> GetEmployeesByTeamSetId(long teamSetId)
        {
            var employees = _employeeRepository.GetAll().Where(x => !x.IsDeleted && x.TeamSetId == teamSetId);
            var teamsets = _teamSetRepository.GetAll().Where(x => !x.IsDeleted);

            var result = employees.LeftJoin<TeamSetModel>((a, b) => a.TeamSetId == b.Id && !b.IsDeleted)
                .Select((a, b) => new EmployeeOutput
                {
                    Id = a.Id,
                    EmployeeCode = a.EmployeeCode,
                    EmployeeName = a.EmployeeName,
                    TeamSetId = a.TeamSetId
                }).ToList();
            int total = result.Count;
            return new ApiPaging<EmployeeOutput>()
            {
                Code = ApiEnums.Success,
                Message = "根据班组ID查询员工列表成功",
                Items = result,
                Total = total
            };
        }
        /// <summary>
        /// 批量修改员工班组
        /// </summary>
        /// <param name="employeeIds">员工ID列表</param>
        /// <param name="teamSetId">班组ID</param>
        /// <returns></returns>
        public ApiResult<int> BatchUpdateEmployeeTeamSet(List<long> employeeIds, long teamSetId)
        {
            if (employeeIds == null || !employeeIds.Any())
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "员工ID列表不能为空！",
                    Data = 0
                };
            }

            var employees = _employeeRepository.GetAll()
                .Where(x => !x.IsDeleted && employeeIds.Contains(x.Id))
                .ToList();

            if (!employees.Any())
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "找不到要更新的员工信息！",
                    Data = 0
                };
            }

            // 批量更新员工的班组ID
            foreach (var employee in employees)
            {
                employee.TeamSetId = teamSetId;
                employee.UpdateTime = DateTime.Now;
            }

            // 批量更新到数据库
            var res = _employeeRepository.UpdateRange(employees);

            if (res > 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = $"批量更新员工班组成功，共更新{res}条记录",
                    Data = res
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "批量更新员工班组失败",
                    Data = 0
                };
            }
        }
    }
} 